import {common} from '../api/url';
import pick from 'lodash.pick';
import {getAction, postAction, putAction} from '../api/manage';

export default  {
  data(){
    return {
      title: '操作', // 标题
      visible: false, // 是否显示
      drawerWidth:800,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      formItemLayout:{
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      modaltoggleFlag:true, // 全屏
      confirmLoading: false, // 提交动画;
      entity:"", //是否重复
      disableSubmit:false,// 禁用提交
      version:new Date().getTime(),
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this);
    this.form.getFieldDecorator('formItems', { initialValue: [], preserve: true });
  },
  mounted(){

  },
  methods:{
    getValidator(required, max, min, pattern, dulicate){
      let t = [];
      if(required){
        t.push({required: true, message: '此字段非空!'});
      }
      if(max){
        t.push({max: max, message: `长度不能超过 ${max} 个字符` })
      }
      if(min){
        t.push({min: min, message: `长度不能小于 ${min} 个字符`})
      }
      if(pattern){
        t.push({pattern: pattern, message: `格式不匹配 ${pattern}`})
      }
      if(dulicate){
        t.push({validator:this.doDulicateCheck, trigger: 'blur'})
      }
      return t;
    },
    getValidatorRolesRequired(max, min=0){
      if(max){
        return [{required: true, message: '此字段非空!'},{ min: min, max: max, message: `长度在 ${min} 到 ${max} 个字符`, trigger: 'blur'}];
      }
      return [{required: true, message: '此字段非空!'}];
    },
    getValidatorRolesMaxLength(max, min=0){
      return [{ min: min, max: max, message: `长度在 ${min} 到 ${max} 个字符`, trigger: 'blur'}];
    },
    getValidatorRolesDulicateCheck(max){
      if(max){
        return [
          { required: true, message: '此字段非空!' },
          { min: 1, max: max, message: `长度在 1 到 ${max} 个字符`, trigger: 'blur' },
          { validator: this.doDulicateCheck}
        ]
      }
      return [
        { required: true, message: '此字段非空!' },
        { validator: this.doDulicateCheck}
      ]
    },


    //窗口最大化切换
    toggleScreen(){
      if(this.modaltoggleFlag){
        this.drawerWidth = window.innerWidth;
      }else{
        this.drawerWidth = 800;
      }
      this.modaltoggleFlag = !this.modaltoggleFlag;
    },
    setEntity(entityName){
      this.entity = entityName;
    },

    // 删除动态表单项
    removeFormItems(k) {
      const { form } = this;
      const keys = form.getFieldValue('formItems');
      if (keys.length === 1) {
        return;
      }
      form.setFieldsValue({
        formItems: keys.filter(key => key !== k),
      });
      this.addFormItemValid();
    },
    // 新增动态表单项
    addFormItems() {
      const { form } = this;
       let keys = form.getFieldValue('formItems');
      this.doAddFormItems(keys);
      form.setFieldsValue({
        "formItems": keys,
      });
      this.addFormItemValid();
    },
    // 实际新增动态表单项，子覆盖
    doAddFormItems(formItemsValue){
      formItemsValue.push({});
    },
    // 动态表单验证
    addFormItemValid(){
      let form = this.form;
      let keys = form.getFieldValue("formItems");
      let fieldsValid = {};
      // 文档
      // keys.forEach((v, index)=>{
      //   fieldsValid[index]={
      //     type:'object',
      //     required:true,
      //     fields:{
      //       equipmentName:{type:'string', required:true, max:200},
      //       equipmentNum:{type:'integer', required:true, min:1}
      //     }
      //   }
      // })
      // form.getFieldDecorator("formItems",{
      //   rules:[
      //     {required: true,
      //       message: '此字段非空!',
      //       type:'array',
      //       len:keys.length,
      //       fields:fieldsValid
      //     },
      //
      //   ]
      // })
    },
    add (param) {
      this.edit(param||{});
    },
    edit (record) {
      this.resetScreenSize();
      this.form.resetFields();
      this.model = Object.assign({}, record);
      this.version = new Date().getTime();
      this.afterFullData();
      this.visible = true;
      this.$nextTick(() => {
        let names = [];
        for(let k in this.form.getFieldsValue()){
          names.push(k);
        }
        this.form.setFieldsValue(pick(this.model, names));
      });
    },
    // 数据填充后
    afterFullData() {

    },
    handleCancel () {
      this.close()
    },
    beforeHandleSubmit(formData){
      return true;
    },
    handleVaildError(err){

    },
    handleSubmit () {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let formData = Object.assign(this.model, values);
          if(!this.beforeHandleSubmit(formData)){
            return;
          }
          that.confirmLoading = true;
          let obj;
          if (!this.model.id) {
            obj = this.saveAdd(formData);
          } else {
            obj = this.saveEdit(formData);
          }
          obj.then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
              that.close();
            }
          }).finally(() => {
            that.confirmLoading = false;
          });
        }else{
          this.handleVaildError(err);
        }
      })
    },
    saveAdd(data){
      return postAction(this.url.add, data);
    },
    saveEdit(data){
      return putAction(this.url.edit, data);
    },
    close(){
      this.$emit('close');
      this.disableSubmit = false;
      this.visible = false;
    },
    // 验证
    doDulicateCheck(rule, value, callback) {
      // rule {field:"", fullField:"", type:""}
      let tableName = this.entity;
      if(! tableName) {
        this.$message.warn("请先设置表名")
        callback("请先设置表名");
      }
      let params = {
        tableName: tableName,
        fieldName: rule.field,
        fieldVal: value,
        dataId: this.model.id,
      };
      getAction(common.dulicateCheck, params).then((res) => {
        if (res.success) {
          callback();
        } else {
          callback(res.message);
        }
      });
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize(){
      let screenWidth = document.body.clientWidth;
      if(screenWidth < 800){
        this.drawerWidth = screenWidth;
      }else{
        this.drawerWidth = 800;
      }
    },
  }

}
